package com.wmx.thread.concurrent;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**********************************
 * @author wmx
 * @date 2019/8/25 22:15
 * @description:
 * @version 1.0
 *
 *
 ************************************/
@Slf4j
public class CountDownLatchExample {
    private final static int threadCount = 200;

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int stamp = i;
            exec.execute(() -> {
                try {
                    doSomeThing(stamp, Thread.currentThread());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            });

        }
        //让主线程等待
        countDownLatch.await();
        //超过指定时间跳过等待
        // countDownLatch.await(10, TimeUnit.MILLISECONDS);

        log.info("所有线程执行完在执行main线程");

        exec.shutdown(); 

    }

    public static void doSomeThing(int stamp, Thread thread) throws InterruptedException {
        Thread.sleep(100);
        log.info("{}", stamp + "======================" + Thread.currentThread().getName());
        Thread.sleep(100);
    }

    private static void test(int threadNum) throws Exception {
        Thread.sleep(100);
        log.info("{}", threadNum + "======================" + Thread.currentThread().getName());
        Thread.sleep(100);
    }
}
